package com.deyuanyun.pic.settings.support.base;


import com.deyuanyun.pic.common.spring.SpringAppliction;
import com.deyuanyun.pic.common.tool.Globals;
import com.deyuanyun.pic.common.util.ApplicationConfigUtil;
import com.deyuanyun.pic.common.util.ConvertUtil;
import com.deyuanyun.pic.common.util.HardWareUtils;
import com.deyuanyun.pic.settings.support.shiro.ShiroUrlUtils;
import com.deyuanyun.pic.settings.support.utils.BaseCodeUtils;
import com.deyuanyun.pic.settings.task.Pool;
import com.deyuanyun.pic.settings.task.run.SMSServiceRun;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager;
import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver;
import org.apache.shiro.web.servlet.AbstractShiroFilter;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.HashMap;
import java.util.Map;

/**
 * User: huanglw
 * Date: 15-3-24
 * Time: 下午5:14
 */
public class ApplicationPropertiesListener implements ServletContextListener {
    protected Logger logger = LogManager.getLogger(this.getClass());
    public static boolean devMod=false;

    public static String code = generateCode();

    /**
     * 根据计算机信息生成code
     * @return
     */
    private static String generateCode() {
        String source = "";
        source += HardWareUtils.getCPUSerial();
        source += HardWareUtils.getMotherboardSN();
        source += HardWareUtils.getHardDiskSN();
        source += HardWareUtils.getMacAddress();
        return new Md5Hash(source, "GW_CODE").toHex();
    }

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        ServletContext servletContext=servletContextEvent.getServletContext();

        try {
            //加载code表
            BaseCodeUtils.loadBaseCode(false);
        } catch (Exception e) {
            logger.error("获取code表报错了!",e);
        }
        
        ShiroFilterFactoryBean shiroFilterFactoryBean= SpringAppliction.getBean(ShiroFilterFactoryBean.class);
        AbstractShiroFilter shiroFilter= null;
        try {
            shiroFilter = (AbstractShiroFilter)shiroFilterFactoryBean.getObject();
        } catch (Exception e) {
            logger.error("",e);
        }

        PathMatchingFilterChainResolver filterChainResolver =(PathMatchingFilterChainResolver)shiroFilter.getFilterChainResolver();
        DefaultFilterChainManager manager =(DefaultFilterChainManager)filterChainResolver.getFilterChainManager();
        //清空老的权限控制
        manager.getFilterChains().clear();
        shiroFilterFactoryBean.getFilterChainDefinitionMap().clear();
        String s= ShiroUrlUtils.getPerString();
        shiroFilterFactoryBean.setFilterChainDefinitions(s);
        //shiroFilterFactoryBean.setFilterChainDefinitions("/monitoring = authc,perms[admin:manage]\n" +
        //        "/login.html  = authc,perms[admin:manage]");
        //重新构建生成
        Map<String, String> chains = shiroFilterFactoryBean.getFilterChainDefinitionMap();
        for(Map.Entry<String, String> entry :chains.entrySet()) {
            String url = entry.getKey();
            String chainDefinition =entry.getValue().trim().replace(" ", "");
            manager.createChain(url,chainDefinition);
        }
        //Map map= shiroFilterFactoryBean.getFilterChainDefinitionMap();
        /*
        logger.info("加载系统参数--需要直接传到页面上去的");
        String linuxUrl="/opt/pic_config/pic_frontend/application.properties";

        Properties props = new Properties();
        try {
            File file=new File(linuxUrl);
            if (file.exists()){
                props.load(new BufferedInputStream(new FileInputStream(file)));
            }else {
                props.load(this.getClass().getResourceAsStream("/properties/application.properties"));
            }

        } catch (FileNotFoundException e) {
            logger.error(e);
        } catch (IOException e) {
            logger.error(e);
        }

        String devModValue=props.getProperty("dev_mod","false");
        devMod = ConvertUtil.coverToBool(devModValue);

        //ServletContext servletContext = servletContextEvent.getServletContext();
        Iterator itr = props.entrySet().iterator();
        TempStoreDataSupport.pushDataf("application.properties",props);
       // Properties p= TempStoreDataSupport.pullDataf("application.properties");
        while (itr.hasNext()) {
            Map.Entry e = (Map.Entry) itr.next();
            servletContext.setAttribute(e.getKey().toString(), e.getValue());
        }
         */

        devMod = ConvertUtil.coverToBool(Globals.getProperties("dev_mod"));
        servletContext.setAttribute("resourcePath", Globals.getProperties("resourcePath"));
        servletContext.setAttribute("gisResourcePath", Globals.getProperties("gisResourcePath"));
        servletContext.setAttribute("File_Server_Path", Globals.getProperties("File_Server_Path"));
        servletContext.setAttribute("gisApiPath", Globals.getProperties("gisApiPath"));
        servletContext.setAttribute("gisServicePath", Globals.getProperties("gisServicePath"));


        String runsms=ApplicationConfigUtil.getConfigByName("IS_RUN_SMS");
        if ("true".equalsIgnoreCase(runsms)){
            //系统启动的时候就开启一个短信监控线程
            Map map=new HashMap();
            map.put("threadNum","init");
            SMSServiceRun serviceRun=new SMSServiceRun();
            serviceRun.setMark(map);
            String threadName = servletContext.getContextPath();
            serviceRun.setThreadName("_" + threadName);
            Pool.threadPoolTaskExecutor.execute(serviceRun);
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }
}
